from typing import Annotated

from fastapi import Depends
from sqlalchemy import Integer, String, and_, cast, delete, func, insert, select, update

from forward.api.admin.orm.lucky.order import ActivityOrderORM
from forward.api.admin.schemas.lucky.activity_order import (
    ActivityOrderAddInSchema,
    ActivityOrderDetailInSchema,
    ActivityOrderDetailOutSchema,
    ActivityOrderListInSchema,
    ActivityOrderSiginInSchema,
    ActivityOrderStatusInSchema,
)
from forward.common.enums import ActivityTypeEnum, PrizeLevelEnum
from forward.dependencies.database import db
from forward.extend.pydantic.result_api import ResultAPI
from forward.model.schemas.lucky.order import ActivityOrderOutSchema
from forward.model.tables.activity import ActivityOrderModel


class ActivityOrderService:
    def __init__(
        self,
        activity_order_orm: Annotated[ActivityOrderORM, Depends()],
    ) -> None:
        self.activity_order_orm = activity_order_orm

    async def lists(self, list_in: ActivityOrderListInSchema):
        where = []
        if list_in.contact_phone is not None:
            where.append(
                func.json_extract(ActivityOrderModel.contact, "$.mobile")

                .like(f"%{list_in.contact_phone}%")
            )
        if list_in.merchant_id is not None:
            print("merchant_id", list_in.merchant_id)
            where.append(
                func.json_extract(ActivityOrderModel.merchant,
                                  "$.id").cast(Integer)
                == list_in.merchant_id
            )
        if list_in.code is not None:
            where.append(
                func.json_extract(ActivityOrderModel.code,
                                  "$.code")
                == list_in.code
            )
        where_clause = and_(*where) if where else None
        pagination = await self.activity_order_orm.lists(
            where=where_clause, page_num=list_in.page_num, page_size=list_in.page_size
        )
        list = []
        for item in pagination.lists:
            data = item.model_dump()
            if item.activity.type == ActivityTypeEnum.QRCODE:
                data["activity_type_text"] = ActivityTypeEnum.get_label(
                    item.activity.type)
                data["prize_level_text"] = PrizeLevelEnum.get_label(
                    item.prize_temp.prize_index if item.prize_temp else 0)
            elif item.activity.type == ActivityTypeEnum.GUAGUALE:
                data["activity_type_text"] = ActivityTypeEnum.get_label(
                    item.activity.type) + f"【{item.code.code if item.code else ''}】"
                data["prize_level_text"] = PrizeLevelEnum.get_label(
                    item.code.prize_index if item.code else 0)
            list.append(ActivityOrderDetailOutSchema(**data))
        return ResultAPI(
            data={
                "lists": list,
                "count": pagination.total,
            }
        )

    async def add(self, add_in: ActivityOrderAddInSchema):
        statement = insert(ActivityOrderModel).values(add_in.model_dump())
        await db.execute(statement)
        return ResultAPI()

    # async def edit(self, edit_in: ActivityOrderEditInSchema):

    #     statement = update(ActivityOrderModel).where(
    #         ActivityOrderModel.id == edit_in.id).values(edit_in.model_dump())
    #     await db.execute(statement)
    #     return ResultAPI()

    async def detail(self, detail_in: ActivityOrderDetailInSchema):
        statement = select(ActivityOrderModel).where(
            ActivityOrderModel.id == detail_in.id
        )
        record = await db.fetch_one(statement)
        return ResultAPI(
            data=ActivityOrderOutSchema.model_validate(
                record, from_attributes=True)
        )

    # async def delete(self, delete_in: ActivityOrderDeleteInSchema):
    #     stetement = delete(ActivityOrderModel).where(
    #         ActivityOrderModel.id == delete_in.id)
    #     await db.execute(stetement)
    #     return ResultAPI()

    async def status(self, status_in: ActivityOrderStatusInSchema):
        statement = (
            update(ActivityOrderModel)
            .where(ActivityOrderModel.id == status_in.id)
            .values(status_in.model_dump())
        )
        await db.execute(statement)
        return ResultAPI()

    async def sigin(self, sigin_in: ActivityOrderSiginInSchema):

        stament = (
            update(ActivityOrderModel)
            .where(ActivityOrderModel.id == sigin_in.id)
            .values(sigin_in.model_dump())
        )
        await db.execute(stament)
        return ResultAPI()

    async def delete_order_by_activity_id(self, activity_id: int):
        statement = delete(ActivityOrderModel).where(
            ActivityOrderModel.activity_id == activity_id
        )
        await db.execute(statement)
        return ResultAPI()
